from urllib import request,parse
import re
import json
import requests
'''
@使用urllib方式爬取有道
'''
def YouDaoUL(keyword):
    url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    data={'i':keyword,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult':' dict',
            'client': 'fanyideskweb',
            'salt':'1534496780337',
            'sign': '520f5dca6a3327897cbd3805aa059409',
            'doctype':'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTIME',
            'typoResult': 'false',}
    data=parse.urlencode(data)
    
    headers={'Content-Length':len(data)}
    req=request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)
    res=request.urlopen(req).read().decode("utf-8")
    myjson=json.loads(res)
    print(myjson['translateResult'][0][0]['tgt'])
'''
@使用requests方式爬取有道
'''
def YouDaoRe(keyword):
    url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    data={'i':keyword,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult':' dict',
            'client': 'fanyideskweb',
            'salt':'1534496780337',
            'sign': '520f5dca6a3327897cbd3805aa059409',
            'doctype':'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTIME',
            'typoResult': 'false',}
    
    req=requests.post(url,data=data)
    res=req.content.decode("utf-8")
    myjson=json.loads(res)
    print(myjson['translateResult'][0][0]['tgt'])
if __name__=='__main__':
    while True:
        keyword=input("请输入要翻译的内容(按q退出):")
        if keyword=='q':
            break
        select=input("请输入爬取方式：1:urllib,2:requests:")
        if select=='1':
          YouDaoUL(keyword)      
        elif select=='2':
          YouDaoRe(keyword)
